using MediatR;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos;
using Work.ErrorCode;

namespace Work.API.Controllers
{
    /// <summary>
    /// 预约管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AppointmentController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<AppointmentController> _logger;

        public AppointmentController(IMediator mediator, ILogger<AppointmentController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 创建预约
        /// </summary>
        /// <param name="request">预约信息</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<ApiResult<int>> Create(CreateAppointmentCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取预约列表（支持多条件查询）
        /// </summary>
        /// <param name="cardNumber">卡号</param>
        /// <param name="patientName">患者姓名</param>
        /// <param name="department">科室</param>
        /// <param name="doctorName">医生</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="recordStatus">病历状态</param>
        /// <returns>预约列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<AppointmentListDto>>> GetAppointments(
            string? cardNumber = null,
            string? patientName = null,
            string? department = null,
            string? doctorName = null,
            DateTime? startDate = null,
            DateTime? endDate = null,
            string? recordStatus = null)
        {
            try
            {
                var query = new GetAppointmentsQuery
                {
                    CardNumber = cardNumber,
                    PatientName = patientName,
                    Department = department,
                    DoctorName = doctorName,
                    StartDate = startDate,
                    EndDate = endDate,
                    RecordStatus = recordStatus
                };
                return await _mediator.Send(query);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询预约列表失败");
                return new ApiResult<List<AppointmentListDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<AppointmentListDto>()
                };
            }
        }
    }
}




